using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Web;

namespace ARF.Web.Controls
{
    public class ListQuery : SiteQuery
    {
        private string _listName;
        private bool _allowNameInQueryString = false;

        public bool AllowNameInQueryString
        {
            get { return _allowNameInQueryString; }
            set { _allowNameInQueryString = value; }
        }

        public string ListName
        {
            get 
            {
                if (AllowNameInQueryString && !string.IsNullOrEmpty(QueryString["ListName"]))
                    return QueryString["ListName"];

                return _listName; 
            }
            set { _listName = value; }
        }

        protected virtual SPList GetList()
        {
            string sListName = ListName;

            if (sListName.StartsWith("/"))
                return SPContext.Current.Site.RootWeb.Lists[sListName.Substring(1)];

            return GetWebForQuery().Lists[sListName];
        }

        public override string Lists
        {
            get
            {
                try
                {
                    return string.Format("<Lists><List ID='{0}'/></Lists>", GetList().ID.ToString());
                }
                catch (Exception ex)
                {
                    Log.Trace("ListQuery: Failed to set the Lists property");
                    Log.Trace(ex);
                    return "";
                }
            }
            set
            {
                base.Lists = value;
            }
        }

        public override string ViewFields
        {
            get
            {
                if (base.ViewFields == "*") return AllFields();

                return base.ViewFields;
            }
            set
            {
                base.ViewFields = value;
            }
        }

        protected string AllFields()
        {
            SPList oList = GetList();
            StringBuilder sb = new StringBuilder();

            string sPrototype = "<FieldRef Name='{0}' />";

            if (oList != null)
            {
                foreach (SPField oField in oList.Fields)
                {
                    if (oField.InternalName != "LinkFilename")
                        sb.Append(string.Format(sPrototype, oField.InternalName));
                }
            }

            return sb.ToString();
        }
    }
}
